package com.yequan.thread.base.volatilepackage;

public class VolatileBarrierExample {

    int a;
    volatile int v1 = 1;
    volatile int v2 = 2;

    public static void main(String[] args) {
        final VolatileBarrierExample volatileBarrierExample = new VolatileBarrierExample();
        new Thread(new Runnable() {
            @Override
            public void run() {
                volatileBarrierExample.readAndWrite();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                volatileBarrierExample.readAndWrite();
            }
        }).start();
    }

    void readAndWrite() {
        //第一个volatile读
        int i = v1;
        //第二个volatile读
        int j = v2;
        //普通写
        a = i + j;
        //第一个volatile写
        v1 = i + 1;
        //第二个volatile写
        v2 = j * 2;

        System.out.println("a=" + a);
        System.out.println("v1=" + v1);
        System.out.println("v2=" + v2);
    }

}
